package mo.tags.stack;

import java.util.Stack;

public class L394 {

    public String decodeString(String s) {
        Stack<Integer> nums = new Stack<>();
        Stack<StringBuilder> strs = new Stack<>();
        int num = 0;
        StringBuilder cur = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            if (Character.isDigit(s.charAt(i))) {
                num = num * 10 + s.charAt(i) - '0';
            } else if (s.charAt(i) == '[') {
                nums.push(num);
                num = 0;
                strs.push(cur);
                cur = new StringBuilder();
            } else if (s.charAt(i) >= 'a' && s.charAt(i) <= 'z') {
                cur.append(s.charAt(i));
            } else if (s.charAt(i) == ']') {
                Integer pop = nums.pop();
                StringBuilder tmp = strs.pop();
                for (int j = 0; j < pop; j++) {
                    tmp.append(cur);
                }
                cur = tmp;
            }
        }
        return cur.toString();
    }



}
